<?php
/**
 * WithdrawModel.class.php
 * 提现管理模型
 *
 * @author  朱伟东
 *
 */

namespace Admin\Model;
use Think\Model;
/**
 * 提现管理模型
 *
 */
class WithdrawModel extends  Model{
    protected $trueTableName = 't_withdraw';
    private $status_titles = array('审核失败','已放款','待审核','待复审','打款失败');
    /**
     * 查询列表
     *
     */
    public function search($status,$state,&$p,$starttime,$endtime) {

        if($status==2){
            $map['t_withdraw.status']  =  array('in',[2,3,4]);
        }else if($status==1){
            $map['t_withdraw.status']  =1;
        }else{
            $map['t_withdraw.status']  =0;
        }
        if((!empty($starttime)) && (!empty($endtime))){
            $map['t_withdraw.create_time'] = array('BETWEEN',array(strtotime($starttime),strtotime($endtime)+86400));
        }
        $map['t_withdraw.target_id']  =0;
        //$map['t_user.role_id']  = $state;
        $order =  't_withdraw.id desc';
        $result = $this
                    ->join('inner join t_user  ON t_user.id=t_withdraw.user_id and t_user.role_id='.$state.'')
                    ->field('t_withdraw.id,user_id,t_withdraw.amount as apply_amount,t_withdraw.create_time,nickname,wallet,t_user.amount as total_amount,t_withdraw.status, t_user.nickname, t_user.truename')
                    ->where($map)->page($p,C('PAGE_COUNT'))->order($order)->select();
        if($result) {
            foreach($result as &$user) {
                if(!empty($user['create_time'])){
                    $user['create_time'] = date("Y-m-d", $user['create_time']);
                }else{
                    $user['create_time'] = '';
                }
                $user['status_title'] = $this->status_titles[$user['status']];
                $user['has_apply'] = $user['total_amount']-$user['wallet'];
		$user['truename'] 	= $user['truename'] ? $user['truename'] : $user['nickname'];
            }
        }
        $count = $this->where($map)->count();
        $page   = new \Think\Page($count,C('PAGE_COUNT'));
        $p  = $page->angular_show();
        return $result;
    }

    /**
     * 查询导出数据
     *
     */
    public function getList($status,$state,$starttime,$endtime) {

        if($status==2){
            $map['t_withdraw.status']  =  array('in',[2,3,4]);
        }elseif($status==1){
            $map['t_withdraw.status']  =  1;
        }else{
            $map['t_withdraw.status']  = 0;
        }
        if((!empty($starttime)) && (!empty($endtime))){
            $map['t_withdraw.create_time'] = array('BETWEEN',array(strtotime($starttime),strtotime($endtime)+86400));
        }
        $map['t_withdraw.target_id']  =0;
        $order =  't_withdraw.id desc';
        $result = $this
            ->join('inner join t_user  ON t_user.id=t_withdraw.user_id and t_user.role_id='.$state.'')
            ->field('t_withdraw.id,nickname, truename,t_withdraw.create_time,t_withdraw.amount as apply_amount,wallet,t_user.amount as total_amount')
            ->where($map)->order($order)->select();
        if($result) {
            foreach($result as &$user) {
                if(!empty($user['create_time'])){
                    $user['create_time'] = date("Y-m-d", $user['create_time']);
                }else{
                    $user['create_time'] = '';
                }
                $user['has_apply'] = $user['total_amount']-$user['wallet'];
            }
        }
        return $result;
    }
    /**
     * 提现审核，放款
     *
     */
    public function change($Id,$status,$content) {
        $user = D('Member');
        if($status==4){
            //复审通过
            $info=$this
                ->join('left join t_user  ON t_user.id=t_withdraw.user_id')
                ->field('t_withdraw.id,user_id,open_id,t_withdraw.amount ,wallet')
            ->where("t_withdraw.id={$Id}")->find();
            $amount = $info['amount'];
            $openId = $info['open_id'];
            $userId = $info['user_id'];

            $userInfo =$user->where("id={$userId}")->find();
            $withdrawInfo =$this->where("id={$Id}")->find();
            if($withdrawInfo['status'] == 1){
                return '审核条目已通过';
            }

            $wxPay =new \Wechat\Util\WxPay();
            //扣税后金额
            $noTaxAmount    = round($amount*(1-C('plat_config.wd_tax_rate')), 2);
            //微信打款
            $ret = $wxPay->transferToUser($openId,$noTaxAmount*100,'用户提现');

            if($ret ===false){
                //打款失败
                $errMsg =$wxPay->errMsg;
                return $errMsg;
            }else{
                //打款成功，向t_money表中插入数据
                $dMoney = new \Wechat\Model\MoneyModel();
                $tradeNo =(string)$ret->partner_trade_no;
                $moneyInfo =$dMoney->addMoneyInfo($userId,$tradeNo,$Id,3,-abs($noTaxAmount));

                //更改提现状态
                $withdrawInfo['status']=1;
                $withdrawInfo['remark']=$content;
                $withdrawInfo['auth_time']=time();
                $withdrawInfo['money_id']=$moneyInfo['id'];
                $withdrawInfo['tax_rate']   = C('plat_config.wd_tax_rate');
                $this->where("id=".$Id)->save($withdrawInfo);

                $success = true;
                $wxTempMsg=\Wechat\Util\WxTempMsg::getInstance();
                $wxTempMsg->withdraw($userInfo,$withdrawInfo,$success);
            }
        }else if($status==0){
            //审核失败
            if( is_array( $Id ) ){
                foreach ($Id as $v){
                    $info=$this
                        ->join('left join t_user  ON t_user.id=t_withdraw.user_id')
                        ->field('user_id,open_id,t_withdraw.amount ,wallet')
                        ->where("t_withdraw.id=".$v)->find();
                    $condition['id']=$info['user_id'];
                    $data['wallet']=$info['wallet']+$info['amount'];
                    $user->where($condition)->save($data);

                    $userInfo =$user->where($condition)->find();
                    $withdrawInfo =$this->where("id={$v}")->find();
                    $success = false;
                    $wxTempMsg=\Wechat\Util\WxTempMsg::getInstance();
                    $wxTempMsg->withdraw($userInfo,$withdrawInfo,$success);
                }
                $data['status']=$status;
                $data['remark']=$content;
                $data['auth_time']=time();
		$data['tax_rate']   = C('plat_config.wd_tax_rate');
                $where =  array('id' => array('in', $Id )) ;
                $this->where($where)->save($data);
            }else{
                $info=$this
                    ->join('left join t_user  ON t_user.id=t_withdraw.user_id')
                    ->field('user_id,t_withdraw.amount ,wallet')
                    ->where("t_withdraw.id={$Id}")->find();
                $condition['id']=$info['user_id'];
                $data['wallet']=$info['wallet']+$info['amount'];
                $user->where($condition)->save($data);

                $data['status']=$status;
                $data['remark']=$content;
                $data['auth_time']=time();
		$data['tax_rate']   = C('plat_config.wd_tax_rate');
                $this->where("id={$Id}")->save($data);

                $userInfo =$user->where($condition)->find();
                $withdrawInfo =$this->where("id={$Id}")->find();
                $success = false;
                $wxTempMsg=\Wechat\Util\WxTempMsg::getInstance();
                $wxTempMsg->withdraw($userInfo,$withdrawInfo,$success);

            }
        }else{
            //初审通过
            if( is_array( $Id ) ){
                $data['status']=$status;
                $data['remark']=$content;
                $data['auth_time']=time();
                $where =  array('id' => array('in', $Id )) ;
                $this->where($where)->save($data);
            }else{
                $data['status']=$status;
                $data['remark']=$content;
                $data['auth_time']=time();
                $this->where("id={$Id}")->save($data);
            }
        }
        return 1;
    }


}
